package cn.kailangtu.serialport;

import android.os.SystemClock;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import android_serialport_api.SerialPort;
import cn.kailangtu.serialportv2.DataAnalysis;
import cn.kailangtu.serialportv2.DataVersion2;
import cn.kailangtu.serialportv2.ReceiveMsgListenerV2;

public class SerialPortApi485 {

    private static String TAG = "SerialPortApi==>";
    private String portName;
    private int baudrate;
    private int flags;
    private LinkedBlockingQueue<String> reportMsgQueue = null;
    private LinkedBlockingQueue<String> sendMsgQueue = null;

    private  OutputStream os;
    private  InputStream is;
    private  SerialPort serial;
    private  int resultSize;

    private  byte[] rxByteArray;

    private ReceiveMsgListenerV2 listener;
    private static boolean isReading = false;


    public SerialPortApi485(){
        reportMsgQueue = new LinkedBlockingQueue<>(500);
        sendMsgQueue = new LinkedBlockingQueue<>(500);
    }


    /***
     * 打开串口
     * @param portName 串口名称，例：/dev/ttyS1
     * @param baudrate 波特率
     * @param flags flag
     * @return
     */
    public boolean openSerialPort(String portName,int baudrate,int flags)
    {
        try {
            this.portName = portName;
            this.baudrate = baudrate;
            this.flags = flags;

            serial = new SerialPort(new File(portName), baudrate, flags);
            os = serial.getOutputStream();
            is = serial.getInputStream();
//            ReadThread readThread = new ReadThread();
//            readThread.start();
            return true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    public void close(){
        serial.close();

    }
//发数据
    public void sendBytes(byte[] data){
        try {

           // Log.d("SERIALAAAAA","SEND DATA:"+CommonUtils.ByteArrayToHexString(data));
            os.write(data);
            os.flush();
//
        } catch (IOException e) {
          //  Log.e(TAG,"send IOException"+e.getMessage());
            e.printStackTrace();
            onListenerErr(e.getMessage());
        } catch(Exception e)
        {
          //  Log.e(TAG,"send IOException"+e.getMessage());
            e.printStackTrace();
            onListenerErr(e.getMessage());
        }
    }


//收数据
    public void shouBytes(ReceiveMsgListenerV2 listener){
        try {
            this.listener = listener;
            ReadThread readThread = new ReadThread();
            readThread.start();
        } catch(Exception e)
        {
         //   Log.e(TAG,"send IOException"+e.getMessage());
            e.printStackTrace();
            onListenerErr(e.getMessage());
        }
    }

    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            if(!isReading) {
                while (!isInterrupted()) {
                    isReading = true;
                    try {
                        byte[] buffer = new byte[255];
                        if (is == null) {
                            return;
                        }
                         SystemClock.sleep(1);
                        int tempSize;
                        tempSize = is.read(buffer);
//                        Log.d("rrrrrrrr","p"+ buffer[0]+ buffer[1]+ buffer[2]);
//                        Log.d("rrrrrrrr","w"+ tempSize);
                        if (tempSize > 0) {
                            onDataReceived(buffer, tempSize);
                        }
                    } catch (IOException e) {
                        //Log.e(TAG, "ReadThread3异常");
                        e.printStackTrace();
                        return;
                    } catch (ModbusError e) {
                        throw new RuntimeException(e);
                    }
                }
                isReading = false;
            }
        }
    }

    private  void onDataReceived(byte[] paramArrayOfByte,
                                       int paramInt) throws ModbusError {
        rxByteArray = CommonUtils.ArrayAppend(rxByteArray, paramArrayOfByte, paramInt);
        if (rxByteArray == null) {
            return;
        }
        String byteStr = CommonUtils.ByteArrayToHexString(rxByteArray);
        Log.e(TAG,"receive msg:"+byteStr);
        resultSize += paramInt;
        if(isCompleteTest())
        {
            resultSize = 0;
            rxByteArray = null;
        }
    }

    private boolean isCompleteTest() throws ModbusError {
      //  Log.d("SerialPortApi485","进了isCompleteTest");
        if(listener != null)
        {
            Log.d("SerialPortApi485","进了isCompleteTest  listener 不是null");
            listener.errorMsg(CommonUtils.ByteArrayToHexString(rxByteArray));
            listener.onReceiveData(rxByteArray);

        }
        return true;
    }
    private void onListenerErr(String err)
    {
        if(listener != null)
        {
            listener.errorMsg(err);
        }
    }


}
